package top.mcwebsite.playandroid.business.search.impl.repository

import android.content.Context
import androidx.datastore.core.CorruptionException
import androidx.datastore.core.DataStore
import androidx.datastore.core.Serializer
import androidx.datastore.dataStore
import com.google.protobuf.InvalidProtocolBufferException
import java.io.InputStream
import java.io.OutputStream
import top.mcwebsite.playandroid.business.search.impl.model.SearchHistoryData

object SearchHistoryDataSerializer : Serializer<SearchHistoryData> {
    override val defaultValue: SearchHistoryData = SearchHistoryData.getDefaultInstance()

    override suspend fun readFrom(input: InputStream): SearchHistoryData {
        try {
            return SearchHistoryData.parseFrom(input)
        } catch (exception: InvalidProtocolBufferException) {
            throw CorruptionException("Cannot read proto.", exception)
        }
    }

    override suspend fun writeTo(t: SearchHistoryData, output: OutputStream) {
        t.writeTo(output)
    }
}

val Context.searchHistoryDataStore: DataStore<SearchHistoryData> by dataStore(
    fileName = "search_history_data.pb",
    serializer = SearchHistoryDataSerializer
)